package clt.com.security;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import clt.com.mapper.PrivRoleMapper;
import clt.com.mapper.SystemMapper;
import clt.com.mapper.UserMapper;
import clt.com.object.User;

/**
 * 权限控制
 * @author zzx
 *
 */
@Configuration
public class ShiroConfiguration {
	//写入，日志信息。
    //private static Logger logger = LoggerFactory.getLogger(ShiroConfiguration.class);
    
    @Bean(name="ShiroRealmImpl")
    public ShiroRealmImpl getShiroRealm(){
    	//实例化 ShiroRealmImpl 类，返回一个ShiroRealmImpl 对象。
        return new ShiroRealmImpl();
    }
    @Bean(name="shrioEhcacheManager")
    public EhCacheManager getEhCacheManager(){
        EhCacheManager ehCacheManager = new EhCacheManager();
        //获取eacache-shiro.xml 文件信息。
        ehCacheManager.setCacheManagerConfigFile("classpath:config/ehcache-shiro.xml");
        return ehCacheManager;
    }

    @Bean(name="lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor(){
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }

    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm((Realm) getShiroRealm());
        defaultWebSecurityManager.setCacheManager(getEhCacheManager());
        return defaultWebSecurityManager;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(getDefaultWebSecurityManager());
        return authorizationAttributeSourceAdvisor;
    }
    
    
    /**
     * 加载shiroFilter权限控制规则（从数据库读取然后配置）
     *
     * @author 
     * @create 2016年7月24日
     */
    private void loadShiroFilterChain(ShiroFilterFactoryBean shiroFilterFactoryBean, SystemMapper systemMapper){
    	//System.out.println("权限数据库");
    	//定义一个 map 集合 存放 权限的URL 地址。
    	Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
       //获取所有系统权限资源信息。从数据看获取所有的权限资源信息。
    	/*Map<String, String> m = new HashMap<>();
    	List<Map<String,String>> permissionList = systemMapper.queryMenuList(m);
    	//遍历从数据查询到的所有  权限资源信息。
        for(Map<String, String> permission:permissionList){
        	//将对应资源权限的地址和名字加入map集合，key 是 权限资源的URL，value 是：authc,perms["+permission.getPermisname()+"]
        	filterChainDefinitionMap.put(permission.get("roleId"), "authc,perms["+permission.get("roleNm")+"]");
        	//写入日志信息。
        	logger.info("##################系统权限【"+permission.get("roleNm")+"】##################");
        }*/
        //在map 集合中插入 初始页面：/home  和备注。
        filterChainDefinitionMap.put("/homePage/homePage", "authc");
        filterChainDefinitionMap.put("/**", "anon");
        //将map 集合传递到 shiroFilterFactoryBean shiro 工厂。
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
    }

    @Bean(name="shiroFilter")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager, SystemMapper systemMapper){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 必须设置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(getDefaultWebSecurityManager());
        // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
        shiroFilterFactoryBean.setLoginUrl("/");
        // 登录成功后要跳转的连接
        shiroFilterFactoryBean.setSuccessUrl("/homePage/homePage");
        // 权限校验失败后要跳转的连接
        shiroFilterFactoryBean.setUnauthorizedUrl("/index");
        //调用上面的方法 load 加载shiroFilter权限控制规则（从数据库读取然后配置）
        loadShiroFilterChain(shiroFilterFactoryBean,systemMapper);
        //返回 shiro 过滤工厂集合。
        return shiroFilterFactoryBean;
    }
}
